package com.renhuikeji.taobaoweb;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;

public class MainActivity extends Activity {
    @BindView(R.id.webview)
    WebView webview;
    String url;
    private long exitTime=-3000;
    private String imgurl="";
    private int downX=0;
    private int downY=0;
    private String imgPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        webview.getSettings().setJavaScriptEnabled(true);
        url="http://www.sqtb5188.com/mobile";
        webview.setWebChromeClient(new MywebChromeClient(this));
        webview.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.d("CCC","onPageStarted;"+url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                Log.d("CCC",error.toString());
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                Log.d("CCC",errorResponse.toString());
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
            }

            @Override
            public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
                super.onUnhandledKeyEvent(view, event);
            }
        });
        webview.loadUrl(url);
        requestPermission();
        initListener();
    }

    private void requestPermission() {
        RxPermissions rxPermissions=new RxPermissions(MainActivity.this);
        rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if(aBoolean){
                        }else{
                            Toast.makeText(MainActivity.this,"已拒绝申请相关权限！",Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    private void initListener() {
        webview.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(final View v) {
                RxPermissions rxPermissions=new RxPermissions(MainActivity.this);
                rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if(aBoolean){
                                   dealImag(v);
                                }else{
                                    Toast.makeText(MainActivity.this,"已拒绝申请相关权限！",Toast.LENGTH_LONG).show();
                                }
                            }
                        });
             return true;
            }
        });
    }

    private boolean dealImag(View v) {
        WebView.HitTestResult result = ((WebView)v).getHitTestResult();
        if (null == result)
            return false;
        int type = result.getType();
        if (type == WebView.HitTestResult.UNKNOWN_TYPE)
            return false;
        if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
            //let TextViewhandles context menu return true;
        }
        final ItemLongClickedPopWindow itemLongClickedPopWindow = new ItemLongClickedPopWindow(MainActivity.this
                ,ItemLongClickedPopWindow.IMAGE_VIEW_POPUPWINDOW
                ,  UIUtils.dip2px(MainActivity.this,360), UIUtils.dip2px(MainActivity.this,90));
        // Setup custom handlingdepending on the type
        switch (type) {
            case WebView.HitTestResult.PHONE_TYPE: // 处理拨号
                break;
            case WebView.HitTestResult.EMAIL_TYPE: // 处理Email
                break;
            case WebView.HitTestResult.GEO_TYPE: // TODO
                break;
            case WebView.HitTestResult.SRC_ANCHOR_TYPE: // 超链接
                // Log.d(DEG_TAG, "超链接");
                break;
            case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
                break;
            case WebView.HitTestResult.IMAGE_TYPE: // 处理长按图片的菜单项
                imgurl = result.getExtra();
                //通过GestureDetector获取按下的位置，来定位PopWindow显示的位置
                itemLongClickedPopWindow.showAtLocation(v,Gravity.CENTER, downX, downY + 10);
                break;
            default:
                break;
        }

        itemLongClickedPopWindow.getView(R.id.item_longclicked_viewImage)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(TextUtils.isEmpty(imgPath)){
                            Toast.makeText(MainActivity.this,"请先保存图片！",Toast.LENGTH_LONG).show();
                        }else{
                            Intent i=new Intent();
                            i.putExtra("path",imgPath);
                            i.setClass(MainActivity.this,ShowImgActivity.class);
                            startActivity(i);
                        }
                    }
                });
        itemLongClickedPopWindow.getView(R.id.item_longclicked_saveImage)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        itemLongClickedPopWindow.dismiss();
                        new SaveImage().execute(); // Android 4.0以后要使用线程来访问网络
                    }
                });
        itemLongClickedPopWindow.getView(R.id.share_qq_tv)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        itemLongClickedPopWindow.dismiss();
                        AndroidShare share=new AndroidShare(MainActivity.this);
                        Bitmap bitmap=string2Bitmap();
                        share.shareQQFriend("","",1,bitmap);
                    }
                });
        itemLongClickedPopWindow.getView(R.id.share_wechat_tv)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        itemLongClickedPopWindow.dismiss();
                        AndroidShare share=new AndroidShare(MainActivity.this);
                        Bitmap bitmap=string2Bitmap();
                        share.shareWeChatFriend("","",1,bitmap);
                    }
                });
        return true;
    }

    /***
     * 功能：用线程保存图片
     *
     * @author wangyp
     */
    private class SaveImage extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String result = "";
            try {
                String sdcard = Environment.getExternalStorageDirectory().toString();
                File file = new File(sdcard + "/Download");
                if (!file.exists()) {
                    file.mkdirs();
                }
                int idx = imgurl.lastIndexOf(".");
                String ext = imgurl.substring(idx);
                file = new File(sdcard + "/Download/" + new Date().getTime() + ext);
                InputStream inputStream = null;
                URL url = new URL(imgurl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(20000);
                if (conn.getResponseCode() == 200) {
                    inputStream = conn.getInputStream();
                }
                byte[] buffer = new byte[4096];
                int len = 0;
                FileOutputStream outStream = new FileOutputStream(file);
                while ((len = inputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                outStream.close();
                result = "图片已保存至：" + file.getAbsolutePath();
                imgPath=file.getAbsolutePath();
                updateAlbum(file);
            } catch (Exception e) {
                result = "保存失败！" + e.getLocalizedMessage();
                imgPath="";
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
        }
    }

    private void updateAlbum(File f ) {
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(this.getContentResolver(),
                    f.getAbsolutePath(), f.getName(), null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
    }

    public Bitmap string2Bitmap(){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        return BitmapFactory.decodeFile(imgPath,options);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if((System.currentTimeMillis()-exitTime)>2000){
                webview.loadUrl(url);
                exitTime=System.currentTimeMillis();
            }else{
                System.exit(0);
            }
//            webview.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
